/**
 *  Copyright (c) 2017-2022 Rushang Co.Ltd All Rights Reserved.
 */
package com.rshang.rsdp.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.rshang.rsdp.annotation.Log;
import com.rshang.rsdp.service.ITbLogService;
import com.rshang.rsdp.service.impl.TbUserServiceImpl;

/**
 * 功能简介：日志切面处理类<br/>
 * @author zhangjun
 * @create 2017年8月10日下午8:41:32
 * 
 */
@Aspect
@Component
public class LogAspect {

	private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
	@Autowired
	ITbLogService logService;
	/**
	 * 日志记录切面方法
	 * @param joinPoint		连接点对象
	 * @return
	 * 		Object
	 * @throws Throwable 
	 */
	@Around(value="@annotation(com.rshang.rsdp.annotation.Log)")
	public Object log(ProceedingJoinPoint joinPoint) throws Throwable{
		logger.debug(joinPoint.getSignature().getName());
		//解析Log注解
		String methodName = joinPoint.getSignature().getName();
        Method method = currentMethod(joinPoint, methodName);
        Log log = method.getAnnotation(Log.class);
        
        if(log!=null)
        {
        		logService.save(joinPoint, methodName, log.module(), log.desc());
        }
        
        return joinPoint.proceed();
        
	}
	
	/**
     * 获取当前执行的方法
     *
     * @param joinPoint  连接点
     * @param methodName 方法名称
     * @return 方法
     */
    private Method currentMethod(ProceedingJoinPoint joinPoint, String methodName) {
        /**
         * 获取目标类的所有方法，找到当前要执行的方法
         */
        Method[] methods = joinPoint.getTarget().getClass().getMethods();
        Method resultMethod = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                resultMethod = method;
                break;
            }
        }
        return resultMethod;
    }
}
